import React from 'react';
import moment from 'moment';
import { Button, Icon, Modal, Card, Input, DatePicker, message, Select, Popconfirm } from 'antd';
import cass from 'classnames';
import s from  './index.module.less';
import taskServer from '../../services/task';
import projectServer from '../../services/project';
import isSuccess from '../../utils/error';
import PickerModal from './PickerModal';

const Option = Select.Option;

const { saveFile: saveProjectFile } = projectServer;
const { uploadFiles, saveFile: saveTaskFile } = taskServer;

export const fileIcon = {
    file: { icon: 'file-unknown', color: '#000' },
    audio: { icon: 'audio', color: '#3991f7' },
    word: { icon: 'file-word', color: '#315794' },
    excel: { icon: 'file-excel', color: '#56b888'},
    ppt: { icon: 'file-ppt', color: '#c45032'},
    pdf: { icon: 'file-pdf', color: '#ee6167'},
    text: { icon: 'file-text', color: '#1890ff'},
    image: { icon: 'picture', color: '#51bfe7'},
    zip: { icon: 'file-zip', color: '#f2b158'}
}

export function renderIcon(name){
    if(/(png|jpeg|jpg|JPEG|JPG)/.test(name)) return fileIcon.image;
    else if(/txt/.test(name)) return fileIcon.text;
    else if(/pdf/.test(name)) return fileIcon.pdf;
    else if(/pptx|ppt/.test(name)) return fileIcon.ppt;
    else if(/xlsx|xls/.test(name)) return fileIcon.excel;
    else if(/(docx|doc)/.test(name)) return fileIcon.word;
    else if(/(mp3|mp4|m4a)/.test(name)) return fileIcon.audio;
    else if(/(rar|zip)/.test(name)) return fileIcon.zip;
    return fileIcon.file
}

const keyArr = ['dateValue', 'nameValue', 'signValue', 'stampValue', 'originValue', 'pageValue', 'partValue', 'remarkValue'];
export function getFileName(v, noExtension){ // 对象为无序集合，使用数组限定排序
    let str = '';
    const obj = {};
    keyArr.forEach(k => {
        if(k === 'dateValue') {
            const date = v[k].split('-').join('')
            str = str + date + '-';
            obj.date = date;
        } else if( k === 'nameValue') {
            str = str + v[k] + '-';
            obj.name = v[k];
        } else if( k === 'signValue' && v[k]) {
            const sign = v[k] ? `${v[k]}签字` : '无签字';
            str = str + sign + '-';
            obj.sign = v[k];
        } else if( k === 'stampValue' && v[k]) {
            const stamp = v[k] ? `${v[k]}盖章` : '无盖章';
            str = str + stamp + '-';
            obj.mark = v[k];
        } else if( k === 'originValue') {
            const unit = (v['pageValue'] || v['partValue'] || v['remarkValue']) ? '原件-' : '原件';
            str = str + v[k] + unit;
            obj.original = v[k];
        } else if( k === 'pageValue' && v[k]) {
            const unit = (v['partValue'] || v['remarkValue'])  ? '页-' : '页';
            str = str + v[k] + unit;
            obj.page = v[k];
        } else if( k === 'partValue' && v[k]) {
            const unit = v['remarkValue'] ? '份-' : '份';
            str = str + v[k] + unit;
            obj.piece = v[k];
        } else if( k === 'remarkValue' && v[k]) {
            const remark = v[k] ? v[k] : '无备注';
            str = str + remark;
            obj.remark = v[k];
        }
    });
    return { 
        filename: noExtension ? str : str + `.${v.response.extension}`, 
        sourcefilename: JSON.stringify(obj)
    };
}

class UploadModal extends React.Component {

    static defaultProps = {
        needReflesh: 'false', // 用于项目模块添加自定义文件夹后刷新文件夹列表
    } 
    
    constructor(props) {
        super(props);
        this.state={
            files: [],
        }
    }

    handleOk = async () => {
        const { files } = this.state;
        
        if(!files.length) {
            message.warning('请选择要上传的文件');
            return;
        }

        // if(files.length > 9) {
        //     message.warning('只可同时最多上传9份文档');
        //     return;
        // }

        this.setState({ confirmLoading: true });
        let canSave = true;
        try {
            files.forEach((f, i) => {
                const { pathValue, dateValue, nameValue, originValue } = f;
                if(!pathValue){
                    throw new Error(`第${i + 1}个文件的保存路径不能为空`);
                }
                if(!dateValue){
                    throw new Error(`第${i + 1}个文件的文件落款/形成日期不能为空`);
                }
                if(!nameValue){
                    throw new Error(`第${i + 1}个文件的文件名不能为空`);
                }
                if(!originValue){
                    throw new Error(`第${i + 1}个文件是否为原件选项不能为空`);
                }
            })
        } catch(e) { // 避免遍历太多，使用try catch捕捉错误的方式结束foreach循环
            message.warn(e.message, 3);
            canSave = false;
        }

        if(!canSave) {
            this.setState({ confirmLoading: false });
            return;
        } 

        // 先上传文件
        const formData = new window.FormData();
        files.forEach(f => formData.append('file', f.fileTarget, f.fileTarget.name));
        const res = await uploadFiles(formData);
        if(isSuccess(res)) {
            // console.log('---uploadFiles---', res);
            this.handleSort(files, res);
        } else {
            this.setState({ confirmLoading: false })
        };

    }

    handleSort = async (files, res) => {
        // 分类处理 
        // 1. 不同类型：上传到文件夹和上传到任务
        // 2. 同样类型但是不同文件之间和不同任务之间
        const toProjectObj = {};
        const innerProjectObj = {};
        const toTaskObj = {};
        files.forEach((f, i) => {
            const { filename, sourcefilename } = getFileName({ ...f, response: res[i] })
            const type = f.type;
            if(type === '1'){ // 上传到文件夹
                // 已项目id为基准分类
                const key = f.project.recid;
                if(toProjectObj[key]){
                    const newFiles = toProjectObj[key].files;
                    if(!newFiles.includes(f.folder.folderid)) { // 判断文件夹id是否重复
                        newFiles.push(f.folder.folderid);
                        toProjectObj[key].files = newFiles;
                    }
                } else {
                    toProjectObj[key] = {
                        projectid: key,
                        stageid: f.stage.stageid,
                        files: [f.folder.folderid]
                    }
                }

                // 已文件夹id为基准分类
                const innerKey = f.folder.folderid;
                if(innerProjectObj[innerKey]){
                    const newItems = innerProjectObj[innerKey].items;
                    newItems.push({
                        filename,
                        sourcefilename,
                        // filetype: 1,
                        folderid: f.folder.folderid,
                        uploadfileid: res[i].fileid,
                        extension: res[i].extension
                    });
                    innerProjectObj[innerKey].items = newItems;
                } else {
                    innerProjectObj[innerKey] = {
                        folderid: f.folder.folderid,
                        foldername: f.folder.foldername,
                        clientid: f.folder.clientid,
                        foldertype: f.folder.foldertype,
                        // innerfoldertype: f.folder.innerfoldertype,
                        items: [
                            {
                                filename,
                                sourcefilename,
                                // filetype: 1,
                                folderid: f.folder.folderid,
                                uploadfileid: res[i].fileid,
                                extension: res[i].extension
                            }
                        ]
                    }
                }
            } else if (type === '2') { // 上传到任务
                const key = f.task.recid;
                if(toTaskObj[key]){
                    const newFiles = toTaskObj[key].files;
                    newFiles.push({
                        filename,
                        sourcefilename,
                        uploadfileid: res[i].fileid
                    });
                    toTaskObj[key].files = newFiles;
                } else {
                    toTaskObj[key] = {
                        taskid: key,
                        files: [
                            {
                                filename,
                                sourcefilename,
                                uploadfileid: res[i].fileid
                            }
                        ]
                     }
                }
            }
        });
        // console.log(toProjectObj, innerProjectObj);
        // 遍历对象为数组
        const uploadProjectData = [];
        for(let key in toProjectObj){
            const files = toProjectObj[key].files.map(k => (innerProjectObj[k]));
            uploadProjectData.push(saveProjectFile({ ...toProjectObj[key], files }));
        }

        const uploadTaskData = [];
        for(let key in toTaskObj){
            uploadTaskData.push(saveTaskFile(toTaskObj[key]));
        }

        const allRes = await Promise.all([...uploadProjectData, ...uploadTaskData]);
        // console.log('allResallResallResallRes-forupload', allRes);

        const { onCancel, onUploadResult } = this.props;
        
        onUploadResult(allRes, () => {
            message.success('上传成功！！！');
            this.setState({
                files: [], confirmLoading: false
            }, onCancel);
        });
    }

    onMinus = (i) => () => {
        const { files } = this.state;
        this.setState({
            files: [
                ...files.slice(0, i),
                ...files.slice(i + 1),
            ]
        });
    }

    onFileChage = (e) => {
        const fileList = e.target.files;
        const { files } = this.state;
        const newFiles = files.concat();
        // 由于原生获取到的FileList数组没有map函数，所以要先用for循环遍历到一个新书组中
        for(let i = 0; i<fileList.length; i++){
            const file = fileList[i];
            if(!files.some(f => f.name === file.name)) {
                const data = {
                    fileTarget: fileList[i],
                    nameValue: fileList[i].name.split('.')[0],
                    signValue: '', stampValue: '', remarkValue: ''
                };
                newFiles.push(data);
            }
        }
        e.target.remove();
		this.setState({ files: newFiles });
    }

    selectFile = () => {
        if (this.input) {
            this.input.click();
            return;
        };
        const input = document.createElement('input');
		input.type = 'file';
        input.multiple = true;
        input.style.display = 'none';
        input.addEventListener('change', this.onFileChage);
        document.body.appendChild(input);
        this.input = input;
		input.click();
    }
    
    onCancel = () => {
        if (this.input) {
            // 移除上传input相关
            this.input.remove();
            this.input.removeEventListener('change', this.onFileChage);
            this.input = undefined;
        }
        
        const { onCancel } = this.props;
        this.setState({ files: []}, onCancel);
    }

    showPickerModal = (i) => {
        this.activeFileIndex = i;
        this.setState({ pickerShow: true });
    }

    hidePickerModal = () => {
        this.setState({ pickerShow: false });
    }

    onPathValueChange = (v, callback) => {
        const { files } = this.state;
        // 设置其它空文件路径默认值为当前选中值
        const newFiles = files.map((f, i) => {
            if(i === this.activeFileIndex || !f.pathValue) {
                return { ...f, ...v };
            }
            return f;
        })
        this.setState({ files: newFiles });
        callback && callback();
    }

    onValueChange = (key, i, onlyNum) => (v, time) => {
        const { files } = this.state;
        const newFiles = files.concat();
        if(onlyNum === 'num') {
            const { value } = v.target;
            const reg = /^-?(0|[1-9][0-9]*)(\.[0-9]*)?$/;
            if (!((!Number.isNaN(value) && reg.test(value)) || value === '' || value === '-')) {
             return;
            }
        }

        let value = v;
        if(key === 'dateValue') value = time;
        else if(key === 'originValue') value = v;
        else value = v.target.value;
        const target = { ...files[i], [key]: value };
        newFiles[i] = target;
        this.setState({ files: newFiles });
    }
  
    render() {
        const { show, needReflesh, projectid, projecttype, stageid, taskid, type } = this.props;
        const { files, confirmLoading, pickerShow } = this.state;

        return (
            <Modal
                title="上传资料（可同时选择多份文件上传）"
                maskClosable={false}
                visible={show}
                width={680}
                footer={[
                    <Button key="cancle" onClick={this.onCancel}>取消</Button>,
                    <Button key="sure" type="primary" onClick={this.handleOk} loading={confirmLoading}>确定</Button>
                ]}
                onCancel={this.onCancel}
                wrapClassName={s.wrapModal}
            >
                <div className={s.content}>
                    <h3>{files.length ? `已选择${files.length}份文件` : '请选择要上传的文件'}</h3>
                    <div className={s.wrap}>
                        {
                            files.map((file, i) => {
                                const { icon, color } = renderIcon(file.fileTarget.name);
                                return (
                                    <Card
                                        key={`file${i}`}
                                        hoverable
                                    >
                                        <div className={s.header}>
                                            <Icon type={icon} className={s.icon} style={{ color }} />
                                            {i + 1}、{file.fileTarget.name}
                                            <Popconfirm
                                                title="删除将不再上传该文件，是否删除？"
                                                okText="确定"
                                                cancelText="取消"
                                                placement="topRight"
                                                onConfirm={this.onMinus(i)}
                                            >
                                                <Icon type="minus-circle" className={s.minus} />
                                            </Popconfirm>
                                        </div>
                                        <div className={s.title}><div/>保存路径 <span className={s.pathReq}>*</span></div>
                                        <div className={s.wrapInput}>
                                            <Input
                                                onClick={() => this.showPickerModal(i)}
                                                value={file.pathValue}
                                                placeholder={'请选择上传的项目文件夹或任务'}
                                                suffix={<Icon type="down" style={{ color: 'rgba(0,0,0,.25)' }} />}
                                            />
                                        </div>
                                        <div className={s.title}><div/>文件名</div>
                                        <div className={s.wrapInput}>
                                            <div className={cass(s.require, s.wrapdate)}>
                                                <DatePicker
                                                    value={file.dateValue ? moment(file.dateValue) : null}
                                                    onChange={this.onValueChange('dateValue', i)}
                                                    className={s.date}
                                                    placeholder="文件落款/形成日期"
                                                />
                                            </div>
                                            <div className={cass(s.require, s.name)}>
                                                <Input
                                                    value={file.nameValue}
                                                    onChange={this.onValueChange('nameValue', i)}
                                                    placeholder="文件名"
                                                />
                                            </div>
                                            <div className={cass(s.require, s.origin)}>
                                                <Select 
                                                    className={s.select}
                                                    value={file.originValue} 
                                                    onChange={this.onValueChange('originValue', i)}
                                                    placeholder="原件"
                                                >
                                                    <Option value="有">有原件</Option>
                                                    <Option value="无">无原件</Option>
                                                </Select>
                                            </div>
                                        </div>
                                        <div className={s.wrapInput1}>
                                            <div className={s.item0}>
                                                <Input
                                                    value={file.signValue}
                                                    onChange={this.onValueChange('signValue', i)}
                                                    placeholder="签字人"
                                                />
                                                <div className={s.text}>签字</div>
                                            </div>
                                            <div className={s.item0}>
                                                <Input
                                                    value={file.stampValue}
                                                    onChange={this.onValueChange('stampValue', i)}
                                                    placeholder="盖章人"
                                                />
                                                <div className={s.text}>盖章</div>
                                            </div>
                                            <div className={cass(s.item0, s.item1)}>
                                                <Input
                                                    value={file.pageValue}
                                                    onChange={this.onValueChange('pageValue', i, 'num')}
                                                    placeholder=""
                                                />
                                                <div className={cass(s.rqeText)}>页</div>
                                            </div>
                                            <div className={cass(s.item0, s.item1)}>
                                                <Input
                                                    value={file.partValue}
                                                    onChange={this.onValueChange('partValue', i, 'num')}
                                                    placeholder=""
                                                />
                                                <div className={cass(s.rqeText)}>份</div>
                                            </div>
                                            <div className={cass(s.item0, s.item2)}>
                                                <Input
                                                    value={file.remarkValue}
                                                    onChange={this.onValueChange('remarkValue', i)}
                                                    placeholder="备注"
                                                />
                                            </div>
                                        </div>
                                    </Card> 
                                )
                             })
                        }
                    </div>
                    <Button type="primary" onClick={this.selectFile}>+ 添加文档</Button>
                    <PickerModal
                        title="请选择保存路径"
                        showfooter
                        type={type}
                        taskid={taskid}
                        stageid={stageid}
                        projectid={projectid}
                        projecttype={projecttype}
                        needReflesh={needReflesh}
                        visible={pickerShow}
                        onOk={this.onPathValueChange}
                        onCancel={this.hidePickerModal}
                    />
                </div>
            </Modal>
        );
    }
}

export default UploadModal